<?php


namespace backend\controllers;


use common\helpers\commonApi;
use common\helpers\TransformApi;
use common\models\Classify;
use common\models\Goods;
use common\models\GoodsSpec;
use common\models\GoodsStock;
use common\models\service\GoodsStockService;
use Yii;
use yii\db\Exception;

/**
 * 商品管理
 * Class GoodsController
 * @package backend\controllers
 */
class GoodsController extends BaseController
{
    private static $addAll = [
        ['name' => '基础设置', 'form' => 'form-basics-data'],
        ['name' => '商品规格', 'form' => 'form-price-data'],
        ['name' => '商品详情', 'form' => 'form-details-data'],
    ];

    public function init()
    {
        parent::init();
        $this->model = Goods::className();
    }

    /**
     * 列表
     * @return array|string
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isPost){
            $data = parent::actionIndex(true,[['delete','=',0]]);
            $classify_id = array_column($data['data'],'classify_id');
            $classify = Classify::getAll(['in','id',$classify_id]);
            $classify = array_column($classify,'name','id');
            foreach ($data['data'] as &$datum){
                $datum['classify'] = $classify[$datum['classify_id']]??'';
                $datum['operlog'] = commonApi::getOperLog($datum);
            }
            return $data;
        }
        $data = Classify::getAll();
        Yii::$app->view->params['data'] = $data;
        return parent::actionIndex();
    }

    /**
     * 新增
     * @return array|string
     */
    public function actionAdd()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $model = new Goods();
            $verif = $model->verif($post);
            if (!$verif['success']){
                return $verif;
            }
            TransformApi::tx(function ()use ($model,$verif){
                $model->load($verif['data'],'');
                if ($model->save()){
                    $str = json_encode($verif['data']['specAll']);
                    $str = str_replace("my_good_id",$model->id,$str);
                    $specArr = json_decode($str,true);
                    foreach ($specArr as &$item){
                        $item['create_time'] = date('Y-m-d H:i:s');
                        $item['update_time'] = date('Y-m-d H:i:s');
                        $item['original_price'] = $item['original_price']??0;
                        $item['trade_price'] = $item['trade_price']??0;
                        $item['ca_price'] = $item['ca_price']??0;
                    }
                    $specModel = new GoodsSpec();
                    $key = array_keys($specArr[0]);
                    $specModel->insertAll($key,$specArr);
                    return commonApi::message('添加成功');
                }
                throw new Exception(commonApi::getModelError($model));
            },$result);
            return $result;
        }
        $classify = Classify::getAll();
        Yii::$app->view->params['classify'] = $classify;
        Yii::$app->view->params['addAll'] = self::$addAll;
        return parent::actionAdd();
    }

    /**
     * 编辑
     * @return array|string
     */
    public function actionEdit()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $id = $post['id']??'';
            $model = Goods::findOne($id);
            if (!$model){
                return commonApi::message('数据不存在',false);
            }
            $verif = $model->verif($post);
            if (!$verif['success']){
                return $verif;
            }
            TransformApi::tx(function ()use ($model,$verif){
                $model->load($verif['data'],'');
                if ($model->save()){
                    $instr = [];
                    $old_sepc = [];
                    foreach ($verif['data']['specAll'] as $item){
                        $item['original_price'] = $item['original_price']??0;
                        $item['trade_price'] = $item['trade_price']??0;
                        $item['ca_price'] = $item['ca_price']??0;
                        if (!empty($item['id'])){
                            $old_sepc[] = $item['id'];
                            GoodsSpec::updateAll(['name'=>$item['name'],'price'=>$item['price'],'trade_price'=>$item['trade_price'],'original_price'=>$item['original_price'],'ca_price'=>$item['ca_price']],['id'=>$item['id']]);
                        }else{
                            $instr[] = [
                                'good_id'=>$model->id,
                                'name'=>$item['name'],
                                'price'=>$item['price'],
                                'original_price'=>$item['original_price'],
                                'create_time'=>date('Y-m-d H:i:s'),
                                'update_time'=>date('Y-m-d H:i:s'),
                                'trade_price'=>$item['trade_price'],
                                'ca_price'=>$item['ca_price'],
                            ];
                        }
                    }
                    if ($old_sepc){
                        GoodsSpec::deleteAll(['and',['not in','id',$old_sepc],['good_id'=>$model->id]]);
                    }
                    if ($instr){
                        $specModel = new GoodsSpec();
                        $key = array_keys($instr[0]);
                        $specModel->insertAll($key,$instr);
                    }
                    return commonApi::message('修改成功',true,[],null,'',['close'=>1]);
                }
                throw new Exception(commonApi::getModelError($model));
            },$result);
            return $result;
        }
        $id = Yii::$app->request->get('id','');
        $spec = GoodsSpec::find()->where(['good_id'=>$id])
            ->orderBy(['id'=>SORT_ASC])
            ->asArray()->all();
        $classify = Classify::getAll();
        Yii::$app->view->params['classify'] = $classify;
        Yii::$app->view->params['addAll'] = self::$addAll;
        Yii::$app->view->params['specAll'] = json_encode($spec);
        return parent::actionEdit();
    }

    public function actionSpec()
    {
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $specAll = $data['specAll']??[];
            return GoodsStockService::setSpec($specAll);
        }
        $id = Yii::$app->request->get('id','');
        $data = GoodsStockService::getSpec($id,$this->campus_id);
        return $this->render('',['data'=>$data,'id'=>$id]);
    }
}